package com.shycloud.mido.opter.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.api.constants.ShoppingStockConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.util.NetworkUtil;
import com.shycloud.mido.common.util.SnowFlakeUtil;
import com.shycloud.mido.member.api.entity.BasicGoodsInfo;
import com.shycloud.mido.opter.api.entity.*;
import com.shycloud.mido.opter.api.vo.StockExchangeGoodsVO;
import com.shycloud.mido.opter.mapper.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.opter.service.StockExchangeGoodsService;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class StockExchangeGoodsServiceImpl extends ServiceImpl<StockExchangeGoodsMapper, StockExchangeGoods> implements StockExchangeGoodsService {

	/** 换货模块 mapper */
	private StockExchangeGoodsMapper exchangeGoodsMapper;
	/** 换货详情模块 mapper */
	private StockExchangeGoodsInfoMapper exchangeGoodsInfoMapper;
	/** 出库模块 mapper */
	private StockSaleOrderMapper stockSaleOrderMapper;
	/** 出库详情模块 mapper */
	private StockSaleOrderDetailMapper stockSaleOrderDetailMapper;
	/** udid模块 mapper */
	private StockDeviceInfoMapper deviceInfoMapper;
	/** 商品详情 mapper */
	private BasicGoodsInfoMapper basicGoodsInfoMapper;

	/**
	 * 新增换货
	 *
	 * @param exchangeGoodsVO
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/9/27 13:18
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean addExchangeGoods(StockExchangeGoodsVO exchangeGoodsVO) {

		StockExchangeGoods stockExchangeGoods = new StockExchangeGoods();
		BeanUtils.copyProperties(exchangeGoodsVO, stockExchangeGoods);
		stockExchangeGoods.setCreateDate(LocalDateTime.now());
		//订单编号
		Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
		long orderNo = new SnowFlakeUtil(1, machineId).nextId();
		stockExchangeGoods.setOrderNo(orderNo);
		//新增换货
		exchangeGoodsMapper.insert(stockExchangeGoods);

		List<Map<String, Integer>> goodsList = exchangeGoodsVO.getGoodsList();

		for (Map<String, Integer> goodsMap : goodsList) {

			StockExchangeGoodsInfo exchangeGoodsInfo = new StockExchangeGoodsInfo();
			//商品ID
			exchangeGoodsInfo.setGoodsId(goodsMap.get("goodsId"));
			//商品数量
			exchangeGoodsInfo.setCount(goodsMap.get("count"));
			//换货单 ID
			exchangeGoodsInfo.setExchangeGoodsId(stockExchangeGoods.getId());
			//新增换货详情
			exchangeGoodsInfoMapper.insert(exchangeGoodsInfo);
		}

		//将udid状态改为作废
		List<Map<String, String>> udids = exchangeGoodsVO.getUdids();

		for (Map<String, String> udid : udids) {
			//获取udid信息
			StockDeviceInfo stockDeviceInfo = deviceInfoMapper.selectById(udid.get("udid"));
			if (stockDeviceInfo != null) {
				//状态改为【作废】
				stockDeviceInfo.setStatus("2");
				//更新
				deviceInfoMapper.updateById(stockDeviceInfo);
			}
		}
		return true;
	}


	/**
	 * 编辑换货单
	 *
	 * @param exchangeGoodsVO
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/9/29 15:07
	 **/
	@Override
	public Boolean saveExchangeGoods(StockExchangeGoodsVO exchangeGoodsVO) {

		StockExchangeGoods stockExchangeGoods = new StockExchangeGoods();
		BeanUtils.copyProperties(exchangeGoodsVO, stockExchangeGoods);
		//更新
		exchangeGoodsMapper.updateById(stockExchangeGoods);

		//先删除详情表
		exchangeGoodsInfoMapper.delete(new QueryWrapper<StockExchangeGoodsInfo>().eq(StockExchangeGoodsInfo.COL_EXCHANGE_GOODS_ID, stockExchangeGoods.getId()));

		List<Map<String, Integer>> goodsList = exchangeGoodsVO.getGoodsList();

		for (Map<String, Integer> goodsMap : goodsList) {

			StockExchangeGoodsInfo exchangeGoodsInfo = new StockExchangeGoodsInfo();
			//商品ID
			exchangeGoodsInfo.setGoodsId(goodsMap.get("goodsId"));
			//商品数量
			exchangeGoodsInfo.setCount(goodsMap.get("count"));
			//换货单 ID
			exchangeGoodsInfo.setExchangeGoodsId(stockExchangeGoods.getId());
			//新增换货详情
			exchangeGoodsInfoMapper.insert(exchangeGoodsInfo);
		}
		return true;
	}

	/**
	 * 获取换货列表
	 *
	 * @param page
	 * @param name
	 * @param startDate
	 * @param endDate
	 * @param isCommit
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.opter.api.vo.StockExchangeGoodsVO>
	 * @author nianhua.jiang
	 * @date 2020/9/27 14:33
	 **/
	@Override
	public IPage<StockExchangeGoodsVO> getExchangeGoodsList(Page page, String name, String startDate, String endDate, String isCommit) {

		IPage<StockExchangeGoodsVO> exchangeGoodsPage = exchangeGoodsMapper.getExchangeGoodsList(page, name, startDate, endDate, isCommit);

		List<StockExchangeGoodsVO> stockExchangeGoodsList = exchangeGoodsPage.getRecords();


		for (StockExchangeGoodsVO stockExchangeGoodsVO : stockExchangeGoodsList) {

			//查询换货详情表
			List<StockExchangeGoodsInfo> stockExchangeGoodsInfos = exchangeGoodsInfoMapper.selectList(new QueryWrapper<StockExchangeGoodsInfo>().eq(StockExchangeGoodsInfo.COL_EXCHANGE_GOODS_ID, stockExchangeGoodsVO.getId()));

			for (StockExchangeGoodsInfo stockExchangeGoodsInfo : stockExchangeGoodsInfos) {

				Map<String, Object> goodsInfo = MapUtil.newHashMap();
				//商品ID
				goodsInfo.put("id", stockExchangeGoodsInfo.getGoodsId());
				//商品名称
				goodsInfo.put("name", exchangeGoodsMapper.getGoodsNameById(stockExchangeGoodsInfo.getGoodsId()));
				//商品数量
				goodsInfo.put("count", stockExchangeGoodsInfo.getCount());

				stockExchangeGoodsVO.getGoodsInfoList().add(goodsInfo);
			}

			//类型：换货
			stockExchangeGoodsVO.setType("换货");
			//数量
			stockExchangeGoodsVO.setCount(exchangeGoodsInfoMapper.getExchangeCount(stockExchangeGoodsVO.getId()));
		}

		return exchangeGoodsPage;

	}

	/**
	 * 提交换货
	 *
	 * @param id
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/9/29 14:54
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean commitExchangeGoods(Integer id) {

		//获取换货信息
		StockExchangeGoods stockExchangeGoods = exchangeGoodsMapper.selectById(id);

		if (stockExchangeGoods == null) {
			throw new BusinessException("换货信息获取失败，请联系管理员");
		}

		//状态改为【已提交】
		stockExchangeGoods.setIsCommit("1");
		exchangeGoodsMapper.updateById(stockExchangeGoods);

		//获取换货商品详情
		List<StockExchangeGoodsInfo> stockExchangeGoodsInfos = exchangeGoodsInfoMapper.selectList(new QueryWrapper<StockExchangeGoodsInfo>().eq(StockExchangeGoodsInfo.COL_EXCHANGE_GOODS_ID, id));

		Integer count = 0;

		for (StockExchangeGoodsInfo goodsInfo : stockExchangeGoodsInfos) {

			StockSaleOrderDetail stockSaleOrderDetail = new StockSaleOrderDetail();
			//商品ID
			stockSaleOrderDetail.setGoodsId(goodsInfo.getGoodsId());
			//订单编号
			stockSaleOrderDetail.setOrderNo(stockExchangeGoods.getOrderNo());
			//商品数量
			stockSaleOrderDetail.setQuantity(goodsInfo.getCount());
			//查询商品详情表获取商品类型
			BasicGoodsInfo basicGoodsInfo = basicGoodsInfoMapper.selectById(goodsInfo.getGoodsId());
			//商品类型
			stockSaleOrderDetail.setType(basicGoodsInfo.getUseType());
			//新增出库详情
			stockSaleOrderDetailMapper.insert(stockSaleOrderDetail);

			count += goodsInfo.getCount();
		}

		//新增出库单
		StockSaleOrder saleOrder = new StockSaleOrder();
		//状态
		saleOrder.setCommitStatus("1");
		//订单编号
		saleOrder.setOrderNo(stockExchangeGoods.getOrderNo());
		//客户 ID（机构）
		saleOrder.setOrgId(stockExchangeGoods.getOrgId());
		//客户 ID（运营商）
		saleOrder.setOptId(stockExchangeGoods.getOptId());
		//联系人
		saleOrder.setContact(stockExchangeGoods.getPhone() + " " + stockExchangeGoods.getLeader());
		//说明
		saleOrder.setComments(stockExchangeGoods.getComment());
		//发货类型 1-销售出货 2-换货出货
		saleOrder.setOutType("2");
		//出库数量
		saleOrder.setOutAmount(count);
		//提单人
		saleOrder.setCreatedBy(stockExchangeGoods.getCreateUser());
		//订单创建时间
		saleOrder.setCreateTime(LocalDateTime.now());
		//订单提交时间
		saleOrder.setCommitTime(LocalDateTime.now());
		//仓库ID
		saleOrder.setWarehouseId(stockExchangeGoods.getWarehouseId());
		//新增出库单
		return stockSaleOrderMapper.insert(saleOrder) == 1;

	}
}

